package org.ucas.kgraph.aop;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 使用AOP记录默认日志
 * @author suemi
 */
@Aspect
@Component
public class SystemLogAspect{

  private Logger logger = Logger.getLogger(getClass());

  @Pointcut("@annotation(org.ucas.kgraph.annotation.SystemControllerLog)")
  public void controllerAspect(){}

  @Pointcut("@annotation(org.ucas.kgraph.annotation.SystemServiceLog)")
  public void serviceAspect(){}

  @Before("controllerAspect()")
  public void doBefore(JoinPoint joinPoint){
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    HttpSession session = request.getSession();

    StringBuilder builder = new StringBuilder();
    builder.append("Request Method: ");
    builder.append(joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()");
    builder.append(";Request URL: "+request.getRequestURL()+" ;");
    builder.append("Request Params: {");
    for (Map.Entry<String,String[]> entry:request.getParameterMap().entrySet()){
      builder.append(entry.getKey()+":");
      builder.append(entry.getValue().length==1?entry.getValue()[0]:entry.getValue());
      builder.append(",");
    }
    builder.append("}");

  }

  @AfterThrowing(pointcut = "serviceAspect()", throwing = "e")
  public void doAfter(JoinPoint joinPoint, Throwable e){
    logger.error("Exception occured: "+e.getMessage(),e);
  }

}
